﻿using AutoMapper;
using MediatR;
using SmartCity.BasicData.Api.Write.Application.Command.Account;
using SmartCity.BasicData.Common;
using SmartCity.BasicData.Domain;
using SmartCity.BasicData.Repo;

namespace SmartCity.BasicData.Api.Write.Application.Handler.Account
{
    public class UpdateAccountHandler : IRequestHandler<UpdateAccountCommand, ApiResult<int>>
    {
        private readonly ILogger<UpdateAccountHandler> logger;
        private readonly IBaseRepository<AccountModel> acccountRepo;
        private readonly IMapper mapper;

        public UpdateAccountHandler(ILogger<UpdateAccountHandler> logger,IBaseRepository<AccountModel> acccountRepo,IMapper mapper)
        {
            this.logger = logger;
            this.acccountRepo = acccountRepo;
            this.mapper = mapper;
        }

        /// <summary>
        /// 更新账号信息 的终结者处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(UpdateAccountCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var account = request.AccountName;

            //判断用户是否重复
            var userCount = acccountRepo.GetAsync(x=>x.AccountName==request.AccountName&&x.Id!=request.Id).Result.Count();
            if (userCount > 0) {
                result.Code = Common.Menus.EnumResultCode.Error;
                result.Msg = "修改失败,账号已存在";
                result.Data = userCount;
                return Task.FromResult(result);
            }
            try
            {

                AccountModel model = mapper.Map<AccountModel>(request);
                
                int i = acccountRepo.UpdateAsync(model).Result;

                if (i > 0)
                {
                    result.Code = Common.Menus.EnumResultCode.Success;
                    result.Msg = "修改成功.";
                    result.Data = i;
                }
                else
                {
                    result.Code = Common.Menus.EnumResultCode.Fail;
                    result.Msg = "修改失败.";
                    result.Data = i;
                }
            }
            catch (Exception e)
            {
                logger.LogError("修改过程中发生错误"+e.Message);
            }

            return Task.FromResult(result);
        }
    }
}
